package com.carpedil.movie.service.impl;

import com.carpedil.client.order.service.FeiginOrderService;
import com.carpedil.client.service.FeiginClientService;
import com.carpedil.common.dto.MovieDTO;
import com.carpedil.movie.entity.Movie;
import com.carpedil.movie.mapper.MovieMapper;
import com.carpedil.movie.service.MovieService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import javax.persistence.StoredProcedureQuery;
import javax.websocket.server.ServerEndpoint;
import java.util.ArrayList;
import java.util.List;

/** @author Administrator */
@Service
@ServerEndpoint("/socketService")
public class MovieServiceImpl implements MovieService {
  @Autowired MovieMapper movieMapper;
  @Autowired FeiginOrderService feiginOrderService;
  @Autowired FeiginClientService feiginClientService;
  @Autowired EntityManager entityManager;

  @Override
  public String check(String movieName) {
    return null;
  }

  @Override
  public boolean updateStorage(String movieName) {
    System.out.println("---------库存-1 ------->");
    return movieMapper.updateStorageByName(movieName) > 0;
  }

  @Override
  public boolean updateStorageByProcedure(String movieName, String orderId) {
    String name = this.executeProcedure(movieName);
    StoredProcedureQuery pro = entityManager.createNamedStoredProcedureQuery("log_pro");
    pro.setParameter("id", orderId);
    pro.setParameter("movieName", name);
    Integer i = (Integer) pro.getOutputParameterValue("i");
    return i > 0;
  }

  @Override
  public List<MovieDTO> getAllMovie() {
    List<Movie> list = movieMapper.list();
    List<MovieDTO> movieDdtos = new ArrayList<>();
    for (Movie movie : list) {
      MovieDTO dto = new MovieDTO();
      BeanUtils.copyProperties(movie, dto);
      movieDdtos.add(dto);
    }
    return movieDdtos;
  }

  @Override
  public MovieDTO findMovieById(Integer movieId) {
    Movie movie = movieMapper.findByMovieId(movieId);
    MovieDTO dto = new MovieDTO();
    BeanUtils.copyProperties(movie, dto);
    return dto;
  }

  @Override
  public boolean updateOrderStatus(String orderId, Integer code) {
    /* feiginOrderService.updateOrderStatus(orderId, code); */
    Integer i = feiginClientService.updateOrderStatus(orderId, code);
    System.out.println("出票成功");
    return i > 0;
  }

  @Override
  public String executeProcedure(String movieName) {
    StoredProcedureQuery procedure = entityManager.createNamedStoredProcedureQuery("movie_pro");
    procedure.setParameter("movieName", movieName);
    String n = procedure.getOutputParameterValue("n").toString();
    return n;
  }
}
